<template>
    <div class="main-container">
        <!--查询数据-->
        <div>
            <el-form :model="searchForm" :inline="true" v-show="searchShow" label-width="68px">
                <el-form-item label="菜单名称">
                    <el-input v-model="searchForm.menuName" placeholder="请输入菜单名称" clearable style="width: 180px"
                        @keyup.enter="handleSearch" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="角色状态" clearable style="width: 120px">
                        <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 按钮区域-- -------------------- -->
        <div class="button-container">
            <div>
                <el-button type="primary" plain :icon="Plus" @click="handleAdd"
                    v-hasPermi="['system:user:add']">新增</el-button>
                <el-button type="info" plain :icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
            </div>
            <div>
                <el-tooltip effect="dark" :content="searchShow ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-button circle :icon="Search" @click="toggleSearch" />
                </el-tooltip>
                <el-tooltip effect="dark" content="刷新" placement="top">
                    <el-button circle :icon="Refresh" @click="refresh" />
                </el-tooltip>
            </div>
        </div>

        <!-- 表格区域-------------------  -----------------------      -->
        <div>
            <el-table v-if="refreshTable" v-loading="loading" :data="tableList" row-key="id"
                :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true"
                    width="160"></el-table-column>
                <el-table-column prop="icon" label="图标" align="center" width="100">
                    <template #default="scope">
                        <!-- <svg-icon :icon-class="scope.row.icon" /> -->
                         <svg-icon
                            v-if="scope.row.icon"
                            slot="prefix"
                            :name="scope.row.icon" 
                            width="18px" 
                            height="18px"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="60"></el-table-column>
                <el-table-column prop="perms" label="权限标识" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="path" label="路由" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="componentPath" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="status" label="状态" width="80">
                    <template #default="scope">
                        <el-tag type="primary" disable-transitions v-if="scope.row.status === 0">
                            正常
                        </el-tag>
                        <el-tag type="danger" disable-transitions v-else>
                            禁用
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" width="160" prop="createTime" :formatter="formatDate">
                </el-table-column>
                <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button link type="primary" :icon="Edit" @click="handleUpdate(scope.row)"
                            v-hasPermi="['system:menu:edit']">修改</el-button>
                        <el-button link type="primary" :icon="Plus" @click="handleAdd(scope.row)"
                            v-hasPermi="['system:menu:add']">新增</el-button>
                        <el-button link type="primary" :icon="Delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['system:menu:remove']">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>

        <!-- 添加或修改配置对话框---------------------------------------------------- -->
        <el-dialog :title="title" v-model="dialogFormVisible" width="680px" append-to-body :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级菜单">
                            <el-tree-select v-model="form.parentId" :data="menuOptions"
                                :props="{ value: 'value', label: 'label', children: 'children' }" value-key="id"
                                placeholder="选择上级菜单" check-strictly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="菜单类型" prop="menuType">
                            <el-radio-group v-model="form.menuType">
                                <el-radio :label="0" v-if="directoryRadioShow">目录</el-radio>
                                <el-radio :label="1">菜单</el-radio>
                                <el-radio :label="2">按钮</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="form.menuType != '2'">
                        <el-form-item label="菜单图标" prop="icon">
                            <el-popover placement="bottom-start" :width="540" trigger="click">
                                <template #reference>
                                    <!-- 通过插槽实现图标选择，默认是一个有图标的输入框 -->
                                    <el-input v-model="form.icon" placeholder="请选择图标">
                                        <template #prefix>
                                            <!-- 判断是否选中了icon -->
                                            <svg-icon v-if="form.icon" slot="prefix" :name="form.icon" width="16px"
                                                height="16px" />
                                            <!-- 如果未选中，显示默认的搜索图标 -->
                                            <el-icon v-else class="el-input__icon">
                                                <search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </template>
                                <!-- 显示选择图标的组件 -->
                                <IconSelect ref="iconSelect" @selected="handleSelect" :active-icon="form.icon" />
                            </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单名称" prop="menuName">
                            <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="显示排序" prop="orderNum">
                            <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType != '2'">
                        <el-form-item>
                            <template #label>
                                <span>
                                    <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                                        <el-icon>
                                            <QuestionFilled />
                                        </el-icon>
                                    </el-tooltip>是否外链
                                </span>
                            </template>
                            <el-radio-group v-model="form.isFrame">
                                <el-radio label="0">是</el-radio>
                                <el-radio label="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType != '2'">
                        <el-form-item prop="path">
                            <template #label>
                                <span>
                                    <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    路由地址
                                </span>
                            </template>
                            <el-input v-model="form.path" placeholder="请输入路由地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType == '1'">
                        <el-form-item prop="componentPath">
                            <template #label>
                                <span>
                                    <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    组件路径
                                </span>
                            </template>
                            <el-input v-model="form.componentPath" placeholder="请输入组件路径" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType != '0'">
                        <el-form-item>
                            <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" />
                            <template #label>
                                <span>
                                    <el-tooltip
                                        content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                                        placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    权限字符
                                </span>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType == '1'">
                        <el-form-item>
                            <el-input v-model="form.query" placeholder="请输入路由参数" maxlength="255" />
                            <template #label>
                                <span>
                                    <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    路由参数
                                </span>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item>
                            <template #label>
                                <span>
                                    <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                                        <el-icon>
                                            <QuestionFilled />
                                        </el-icon>
                                    </el-tooltip>
                                    菜单状态
                                </span>
                            </template>
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                dict.label
            }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onDialogFormConfirm">确 定</el-button>
                    <el-button @click="onDialogFormCancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Search, Refresh, Plus, Delete, Edit, Sort, QuestionFilled, } from '@element-plus/icons-vue'
import { ref, onUnmounted, nextTick } from 'vue'
import { menuTreeselect, listTreeService, addMenuService, getMenuById, updateMenuService, deleteMenuService } from '@/api/sys/menu'
import { ElMessage, ElMessageBox } from "element-plus"
// 导入图标选择组件
import IconSelect from '@/components/IconSelect/index.vue'

onUnmounted  (() => {
    //console.log("beforeUnmount----------------------------------------------------")
})

// 日期格式化
const formatDate = (row, column) => {
    const date = new Date(row[column.property]);
    return formatDateString(date);
};

const formatDateString = (date) => {
    const year = date.getFullYear();
    const month = pad2(date.getMonth() + 1);
    const day = pad2(date.getDate());
    const hours = pad2(date.getHours());
    const minutes = pad2(date.getMinutes());
    const seconds = pad2(date.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const pad2 = (number) => {
    return (number < 10 ? '0' : '') + number;
};
// 查询区域   -----------------------------------------------------
// 查询参数
const searchForm = ref({})
// 是否显示
const searchShow = ref(true)
// 状态 0：可用， 1: 不可用
const sys_normal_disable = [
    {
        label: "可用",
        value: 0
    },
    {
        label: "不可用",
        value: 1
    }
]
// 重置查询表单
const resetSearch = () => {
    searchForm.value.menuName = ''
    searchForm.value.status = 0
    getList()
}
// 查询事件
const handleSearch = () => {
    getList()
}

// 操作按钮区域----------------------------------------------------------------
// 操作区显示隐藏控制
const toggleSearch = () => {
    // console.log("toggleSearch--------------search.valeue", searchShow.value)
    if (searchShow.value) {
        searchShow.value = false
        return
    }
    searchShow.value = true
}
// 刷新
const refresh = () => {
    getList()
}

const directoryRadioShow = ref(true)

// 添加
const handleAdd = (row) => {
    getMenuTreeselect()
    if (row != null && row.id) {
        form.value.parentId = row.id;
        directoryRadioShow.value = false;
    } else {
        form.value.parentId = 0;
        directoryRadioShow.value = true
    }
    title.value = addTite
    isAdd.value = true
    dialogFormVisible.value = true
}

// 修改
const handleUpdate = async (row) => {
    getMenuTreeselect()
    const roleId = row.id
    let result = await getMenuById(roleId)
    form.value = result.data
    //console.log('getMenuById form.value', form.value)
    //console.log("handleUpdate", roleId)
    title.value = updateTite
    isAdd.value = false
    dialogFormVisible.value = true
}
/** 删除按钮操作 */
const handleDelete = (row) => {
    const menuId = row.id;
    ElMessageBox.confirm('确认要删除吗？', '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 删除
        //.log("delete===== ids", menuId)
        let result = await deleteMenuService(menuId)
        if (result.code == 0) {
            ElMessage.success(result.message ? result.message : '删除成功')
            getList()
        } else {
            ElMessage.error(result.message ? result.message : '删除失败')
        }
    })
        .catch(() => { })
}
const handleImport = () => {

}
const handleExport = () => {

}


// 查询
const getList = async () => {
    //console.log("getList:", searchForm.value);
    try {
        const result = await listTreeService(searchForm.value)
        // console.log("getList:", result.data)
        tableList.value = result.data;
        loading.value = false;
    } catch (err) { }
    //console.log("tableData:", tableData);
}
getList()


// 表格区域----------------------------------------------------------------
// 表格数据
const refreshTable = ref(true)
const loading = ref(true)
const isExpandAll = ref(false);
const tableList = ref()
const ids = ref([]);

/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}
// 权限分配
const handleAuthRole = (row) => {


}

/** 添加修改相关表单----------------------------------------- */
// 角色树
const menuOptions = ref([{
    value: 0,
    label: '主目录',
}])

// 角色下拉选择数据
let selectIds = ref([])
const roleOptions = ref()
const form = ref({
    menuType: 0,
    isFrame: "1",
    visible: "0",
    status: ""
})
let addTite = "添加菜单"
let updateTite = "修改菜单"
const title = ref(addTite)
const isAdd = ref(true)
const dialogFormVisible = ref(false)

// 重置对话框表单
const restForm = () => {
    form.value = {}
    form.value.menuType = 0
    form.value.isFrame = '1'
    // form.value.status = 0
    title.value = addTite
    isAdd.value = true
    ruleFormRef.value.resetFields()
}

// 提交对话框表单按钮事件
const onDialogFormConfirm = async () => {
    //1.验证表单
    if (!ruleFormRef.value) return
    //2.提交表单
    await ruleFormRef.value.validate((valid) => {
        if (valid) {    // 校验成功
            confirm()
        }
    })
}
// 取消对话表单框按钮事件
const onDialogFormCancel = () => {
    //console.log("cancel......")
    dialogFormVisible.value = false
    restForm()
}

// 选择图标
function handleSelect(name) {
    //console.log("handleSelect=====>", name);
    form.value.icon = name;
}

/** 查询菜单树结构 */
const getMenuTreeselect = async () => {
    try {
        let result = await menuTreeselect()
        // console.log("getMenuTreeselect", result.data)
        menuOptions.value[0].children = result.data
        //console.log("getMenuTreeselect  value", menuOptions.value)
    } catch (e) { }
}

// 提交表单
const confirm = async () => {
    //console.log("confirm-------")
    if (isAdd.value) {
        //console.log("confirm-add------")
        // 添加
        try {   // 添加成功
            let result = await addMenuService(form.value)
            // console.log("addmenu-------------",result)
            // 关闭弹窗，清空表单
            ElMessage.success(result.message ? result.message : '添加成功')
            dialogFormVisible.value = false
            restForm()
            getList()
            //console.log("result-------")
        } catch (error) { //console.log("error", error) 
        }
    } else {
        //console.log("update=======")
        //修改
        try {   // 修改成功
            let result = await updateMenuService(form.value)
            ElMessage.success(result.message ? result.message : '修改成功')
            // 关闭弹窗，清空表单
            dialogFormVisible.value = false
            restForm()
            getList()
        } catch (error) { }
    }

}

/** 表单校验 */
const ruleFormRef = ref(null)   // 定义表单组件的引用
const rules = ref({
    menuType: [{ required: true, message: "菜单类型不能为空", trigger: "blur" }],
    menuName: [{ required: true, message: "菜单名不能为空", trigger: "blur" }],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
    componentPath: [{ required: true, message: "组件路径不能为空", trigger: "blur" }],
})




</script>